package com.ling.controller;

import com.ling.pojo.User;
import com.ling.service.UserService;
import com.ling.utils.VerifyUtil;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 编程之外
 * @company lingStudy
 * @create 2020-07-09 10:18
 */
@RestController
@CrossOrigin   //允许跨域
public class UserController {

    //生成验证码图片==》响应一个 base64 字符串
    @GetMapping("/getImage")
    public String getImageCode(HttpServletRequest request) throws IOException {
        //1.使用工具类生成验证码(包括image和code)
        Map<String, Object> imageCode = VerifyUtil.createImageCode();
        String code = (String) imageCode.get("code");

        //2.将验证码放入servletContext作用域（前后端分离是没有session概念的）
        request.getServletContext().setAttribute("yCode", code);

        BufferedImage image = (BufferedImage) imageCode.get("image");
        //3.将图片转化为base64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //5.响应给浏览器  ImageIO ：工具类
        ImageIO.write(image, "png", outputStream);
        String encode = Base64Utils.encodeToString(outputStream.toByteArray());

        return encode;
    }

    @Autowired
    UserService userService;

    //用户注册
    // 这里必须加 @RequestBody 注解才能拿到前端传递的user对象，
    // 因为前端的 axios 传递数据使用的是 json 格式，这里使用@RequestBody将json字符串转换为对象
    // code：前端输入的验证码，request：为了拿到之前servletContext中存放的验证码yCode对象
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user, String code, HttpServletRequest request) {
        System.out.println("前端传来的user：" + user);
        System.out.println("前端传来的code：" + code);

        Map<String, Object> map = new HashMap<>();
        // try/catch捕捉异常 快捷键 CTRL+ALT+T
        try {
            String yCode = (String) request.getServletContext().getAttribute("yCode");
            // 比对验证码
            if (yCode.equalsIgnoreCase(code)) {
                //调用业务方法
                userService.saveUser(user);
                map.put("state", true);
                map.put("msg", "提示：注册成功！");
                map.put("username", user.getUsername());
            } else {
                throw new RuntimeException("验证码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            // e.getMessage() 可拿到对应的异常信息，包括serviceimpl中抛出的异常（该用户已存在！）
            map.put("msg", "提示：" + e.getMessage());
        }
        return map;
    }

    //登录
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        System.out.println("前端传来的user："+user);
        Map<String, Object> map = new HashMap<>();
        try {
            User userDB = userService.login(user);
            map.put("userDB",userDB);
            map.put("state",true);
            map.put("msg","登录成功！");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

}
